package C049;

import java.util.Arrays;

/**
 * ClassName: C02
 * Package: C049
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/17 09:03
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {
    public static void main(String[] args) {
//        System.out.println(lengthOfLongestSubstring(" "));
//        System.out.println(lengthOfLongestSubstring("abcabcbb"));
        System.out.println(lengthOfLongestSubstring("tmmzuxt"));
        System.out.println(lengthOfLongestSubstring2("tmmzuxt"));
//        System.out.println(lengthOfLongestSubstring2(" "));
//        System.out.println(lengthOfLongestSubstring2(" "));



        int a = -1;
        if(a++ < 0) {
            System.out.println(a);
        }
        if(a++ < 0) {

        }
        System.out.println(a);
    }

    public static int lengthOfLongestSubstring(String s) {
        char[] charArray = s.toCharArray();
        int[] arr = new int[256];
        Arrays.fill(arr, -1);
        int res = 0;
        for (int i = 0, j = 0; i < charArray.length; i++) {
            if(arr[charArray[i]] == -1 || arr[charArray[i]] < j) {
                res = Math.max(res, i - j + 1);
                arr[charArray[i]] = i;
            } else {
                res = Math.max(res, i - j);
                j = arr[charArray[i]] + 1;
                arr[charArray[i]] = i;
            }
        }
        return res;
    }



    public static int lengthOfLongestSubstring2(String str) {
        char[] s = str.toCharArray();
        int n = s.length;
        // char -> int -> 0 ~ 255
        // 每一种字符上次出现的位置
        int[] last = new int[256];
        // 所有字符都没有上次出现的位置
        Arrays.fill(last, -1);
        // 不含有重复字符的 最长子串 的长度
        int ans = 0;
        for (int l = 0, r = 0; r < n; r++) {
            l = Math.max(l, last[s[r]] + 1);
            ans = Math.max(ans, r - l + 1);
            // 更新当前字符上一次出现的位置
            last[s[r]] = r;
        }
        return ans;
    }
}
